<?php
namespace Admin\Model;
use Think\Model;
use Think\Page;
use Think\Verify;

class AdminModel extends Model {
	protected $tableName='Admin';
	//表单验证的规则
	protected $_validate=array(
		array('username','require','用户名不能为空',1),
		array('password','require','密码不能为空',1,'regex',1),
		array('password','require','密码不能为空',1,'regex',4),
		array('username','','用户名已经存在',1,'unique',1),
		array('username','','用户名已经存在',1,'unique',2),
		//这个只有登陆时验证
		array('chk_code','_chkCode','验证码不正确',1,'callback',4)
	);	
	//钩子函数
	protected function _before_insert(&$data, $options){
		$data['password']=md5($data['password']);
	}
	//钩子函数
	protected function _before_update(&$data, $options){
		if($data['password']){
			$data['password']=md5($data['password']);			
		}else{
			unset($data['password']);
		}
		
	}
	
	public function search(){
		$where=1;
		if($un=I('get.un')){
			$where.=' AND username like "%'.$un.'%"';
		}
		if($id=I('get.id')){
			$where.=' and id='.$id;
		}
		$perpage=15;
		$totalRecord=$this->where($where)->count();
		$page=new Page($totalRecord,$perpage);
		
		return array(
			'data'=>$this->where($where)->limit($page->firstRow,$page->listRows)->order('id asc')->select(),
			'page'=>$page->show()
		);
	}
	
	protected function _chkCode($code){
		$verify=new Verify();
		return $verify->check($code,'');
	}
	public function login(){
		//根据用户名查询用户是否存在
		$username=I('username');
		$password=I('password','',trim);
		$db=M('admin');
		//$where['username']=$username;
		$res=$db->where("username='$this->username'")->find();
		$code=I('chk_code','',trim);
		
		if($res){
			//再比较密码是否正确
			if($res['password'] ==md5($password) ){
				session('id',$res['id']);
				session('username',$res['username']);
				return TRUE;
			}else{
				return 2;
			}
		}else{
			return 1;
		}
		
	}
	
	public function logout(){
		session(null);
	}
}